<?php

namespace backend\controllers;

use common\services\AdServices;
use Yii;
use common\models\Ad;
use yii\data\ActiveDataProvider;
use backend\base\BaseBackController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * AdController implements the CRUD actions for Ad model.
 */
class AdController extends BaseBackController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Ad models.
     * @return mixed
     */
    public function actionIndex()
    {
        $params = Yii::$app->request->queryParams;
        $params['defaultPageSize'] = $this->defaultPageSize;
        $service = new AdServices();
        $result = $service->search($params);

        return $this->render('index', [
            'dataProvider' => $result,
            'params' => $params,
        ]);
    }

    /**
     * Displays a single Ad model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Ad model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Ad();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Ad model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Ad model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Ad model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Ad the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Ad::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * @return array|Response
     */
    public function actionBatchDelete()
    {
        if (isset($_POST['datalist']) && Yii::$app->request->isPost) {
            $keys = $_POST['datalist'];
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                Ad::deleteAllByKid($keys);
                return ['result'=>'success'];
            }
            catch (\Exception $ex)
            {
                return ['result'=>'failure', 'message' => $ex->getMessage()];
            }
        }
        else
        {
            return $this->redirect(['index']);
        }
    }

    /**
     * @return array|Response
     */
    public function actionBatchUpdateOrder()
    {
        if (isset($_POST['orders']) && Yii::$app->request->isPost) {
            $orders = $_POST['orders'];
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                foreach ($orders as $key => $val){
                    $model = Ad::findOne($key);
                    $model->order = $val;
                    $model->update();
                }
                return ['result' => 'success'];
            }
            catch (\Exception $ex)
            {
                return ['result'=>'failure'];
            }
        }
        else
        {
            return $this->redirect(['index']);
        }
    }

    public function actionStatus($id, $status)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        if ( Yii::$app->request->isPost) {
            $model = Ad::findOne($id);
            $model->status = $status;
            $model->save();
            return ['result' => 'success'];
        }
        else
        {
            return ['result' => 'failure'];
        }
    }
}
